import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Goods from '../views/Goods.vue'
import Users from '../views/Users.vue'
import store from '@/store'
Vue.use(VueRouter)

let router = new VueRouter({

    routes:[
        {
            name:'main',
            path:'/',
            component:()=>import('../views/Main.vue'),
            redirect: '/home',
            children:[            
            ]
        },
        {
            name:'login',
            path:'/login',
            component:()=>import('../views/Login.vue')
        }
    ]
})

router.beforeEach((to, from, next)=>{
    store.commit('user/getToken')
    const token = store.state.user.token
    if(!token && to.name!=='login'){
        next({name:'login'})
    } 
    else if(token && to.name === 'login'){
        next({ name: 'home'})
    }
    else {
        next()
    }
})

export default router